/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package clienteddns;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
import javax.swing.JOptionPane;

/**
 *
 * @author roberto
 */
public class CadastrarHost extends javax.swing.JFrame {

    /**
     * Creates new form CadastrarHost
     */
    
    private String servidor = new String();
    private String http = new String();

    public String getHttp() {
        return http;
    }

    public void setHttp(String http) {
        this.http = http;
    }
    
    public CadastrarHost() {
        initComponents();
    }

    public String getServidor() {
        return servidor;
    }

    public void setServidor(String servidor) {
        this.servidor = servidor;
    }
    
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtnome = new javax.swing.JTextField();
        cbNat = new javax.swing.JComboBox();
        cbIp = new javax.swing.JComboBox();
        txtEmail = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        pwdSenha = new javax.swing.JPasswordField();
        erro = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();

        setTitle("Cadastrar novo host");

        jLabel1.setText("Nome do Host");

        jLabel2.setText("Qual IP Guardar");

        jLabel3.setText("Vesão IP");

        jLabel4.setText("Confirme Email");

        jLabel5.setText("Confirme Senha");

        cbNat.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Externo", "Interno" }));

        cbIp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "IPv4", "IPv6" }));

        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        erro.setForeground(new java.awt.Color(237, 10, 10));
        erro.setEnabled(false);

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(erro)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))
                        .addGap(29, 29, 29)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cbNat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cbIp, 0, 80, Short.MAX_VALUE))
                            .addComponent(txtEmail)
                            .addComponent(txtnome)
                            .addComponent(pwdSenha)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtnome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cbIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbNat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(pwdSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(erro)
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        try{
            ClienteDDNS c = new ClienteDDNS();
            int nat,ipType;
            String ip = new String();
            
            if(cbNat.getSelectedItem().equals("Interno")){
                nat = 1;
            }else{
                nat = 2;
            }
            if(cbIp.getSelectedItem().equals("IPv6")){
                ipType = 2;
            }else{
                ipType = 1;
            }
            
            erro.setText(" ");
            
            Enumeration nis = null;  
        try {  
            nis = NetworkInterface.getNetworkInterfaces();  
        } catch (SocketException e) {  
            e.printStackTrace();  
          }  
          
        while (nis.hasMoreElements()) {    
            NetworkInterface ni = (NetworkInterface) nis.nextElement();    
            Enumeration ias = ni.getInetAddresses();  
            while (ias.hasMoreElements()) {    
                InetAddress ia = (InetAddress) ias.nextElement();  
                if (ni.getName().equals("wlan0")){   
                  ip =ia.getHostAddress();
                  System.out.println(ip);
                    if(c.validateIp(ip)){
                        break;
                    }
                }
            }    
        }
            URL url = new URL(getHttp()+"://"+servidor+"/cgi-bin/si.cgi?serviceType=2&email="+txtEmail.getText()+"&password="+pwdSenha.getText()+"&hostName="+txtnome.getText()+"&ip="+ip+"&ipType="+ipType+"&nat="+nat);
            c.registerMyHostnameVerifier();
            System.out.println(getHttp()+"://"+servidor+"/cgi-bin/si.cgi?serviceType=2&email="+txtEmail.getText()+"&password="+pwdSenha.getText()+"&hostName="+txtnome.getText()+"&ip="+ip+"&ipType="+ipType+"&nat="+nat);
            InputStreamReader inputReader = new InputStreamReader( url.openStream() );
            BufferedReader bufferedReader = new BufferedReader( inputReader );
            String r = c.getValue(bufferedReader);
            System.out.println(r+servidor);
            if(r.equals("Host Cadastrado com Sucesso")){
                JOptionPane.showMessageDialog(null, "Host Cadastrado com Sucesso","Host Cadastrado com Sucesso",JOptionPane.INFORMATION_MESSAGE);
                dispose(); 
                InicialCliente a = new InicialCliente();
                a.setHttp(getHttp());
                a.setServidor(servidor);
                a.setVisible(true);
            }else{
                JOptionPane.showMessageDialog(null, "Erro no Cadastro do Host","Erro no Cadastro do Host",JOptionPane.ERROR_MESSAGE);
                erro.setText(r);
                erro.setVisible(true);
             }
            //TimeUnit.SECONDS.sleep(5);
       }catch (Exception e) {
                    System.out.println( e.getMessage() );
            }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dispose();
        InicialCliente a = new InicialCliente();
        a.setHttp(getHttp());
        a.setServidor(getServidor());
        a.setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastrarHost.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastrarHost.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastrarHost.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastrarHost.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CadastrarHost().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cbIp;
    private javax.swing.JComboBox cbNat;
    private javax.swing.JLabel erro;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPasswordField pwdSenha;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtnome;
    // End of variables declaration//GEN-END:variables
}
